﻿using System;
using System.Web;
using NHibernate;
using NHibernate.Context;
using Ornament.NHibernates;

namespace Ornament.Web
{
    internal class NHibernateSessionModule : IHttpModule
    {
        #region IHttpModule Members

        public void Init(HttpApplication context)
        {
            context.Error += ContextError;
            context.EndRequest += ApplicationEndRequest;
            context.BeginRequest += ApplicationBeginRequest;
        }

        public void Dispose()
        {
        }

        #endregion

        private void ContextError(object sender, EventArgs e)
        {
            ISession currentSession = CurrentSessionContext.Unbind(SessionManager.Instance.GetSessionFactory());
            if (currentSession != null && currentSession.Transaction != null)
            {
                if (!currentSession.Transaction.WasRolledBack && currentSession.Transaction.IsActive)
                {
                    currentSession.Transaction.Rollback();
                }
            }
        }

        private void ApplicationBeginRequest(object sender, EventArgs e)
        {

            var session = SessionManager.Instance.CurrentSession;

        }

        private void ApplicationEndRequest(object sender, EventArgs e)
        {
            ISession currentSession = SessionManager.Instance.CurrentSession;
            if (currentSession == null)
                return;
            if (currentSession.Transaction != null && currentSession.Transaction.IsActive)
            {
                currentSession.Transaction.Commit();
            }
            currentSession.Flush();
            SessionManager.Instance.CleanUp();
        }
    }
}